/*
 * @Author: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @Date: 2025-07-01 14:16:46
 * @LastEditors: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @LastEditTime: 2025-09-24 14:16:27
 * @FilePath: \keep_motion_api\models\course\courseProgress.model.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const { escapeRegex } = require('@/utils');

// 课程进度模型
const courseProgressSchema = new Schema({
  user_id: { 
    type: Schema.Types.ObjectId, 
    ref: 'User',
    required: true 
  },
  course_id: { 
    type: Schema.Types.ObjectId, 
    ref: 'Course',
    required: true 
  },
  completed_lessons: [{
    lesson_id: Schema.Types.ObjectId,
    completed_at: Date
  }],
  progress_percentage: { type: Number, default: 0 },
  last_accessed: Date,
  last_lesson_completed: Date,
  total_time_spent: { type: Number, default: 0 }
});
courseProgressSchema.statics.getProgress = async function (user_id, user_name, course_id, title, offset = 0, limit = 10) {
 try {
    const query = {};
    if (title) {
      const parentQuery = {};
      const { Course } = require('./');
      const escapedTitle = escapeRegex(title);
      parentQuery.title = { $regex: escapedTitle, $options: 'i' };  
      const rows = await Course.find(parentQuery).lean();
      if (rows.length === 0) return { total: 0, rows: [] };
      const course_ids = rows.map(item => item._id);
      query.course_id = {$in: course_ids};
    }
    if(user_name) {
      const parentQuery = {};
      const { User } = require('../user');
      const escapedUserName = escapeRegex(user_name);
      parentQuery.name = { $regex: escapedUserName, $options: 'i' };  
      const rows = await User.find(parentQuery).lean();
      if (rows.length === 0) return { total: 0, rows: [] };
      const user_ids = rows.map(item => item._id);
      query.user_id = {$in: user_ids};
    }
    if(course_id){
      query.course_id = course_id;
    }
    if(user_id){
      query.user_id = user_id;
    }
    // 先统计符合条件的记录总数
    const total = await this.countDocuments(query);
    // 再进行分页查询
    const rows = await this.aggregate([
      { $match: query },                   // 匹配查询条件
      { $skip: Number(offset) },           // 分页跳过
      { $limit: Number(limit) },           // 分页限制
      // 关联查询（相当于 populate）
      { $lookup: {
        from: 'courses',               // 关联的集合名（通常是模型名小写复数）
        localField: 'course_id',           // 本地关联字段
        foreignField: '_id',             // 关联集合的匹配字段
        as: 'courseInfo'                   // 临时存储关联数据的字段
      }},
      {$lookup: {
        from: 'users',               // 关联的集合名（通常是模型名小写复数）
        localField: 'user_id',           // 本地关联字段
        foreignField: '_id',             // 关联集合的匹配字段
        as: 'userInfo'                   // 临时存储关联数据的字段
      }},
      { $unwind: '$userInfo' },            // 展开数组（如果是一对一关系）
      { $unwind: '$courseInfo' },            // 展开数组（如果是一对一关系）
      // 投影（展平字段 + 筛选）
      { $project: {
      // 保留原文档字段
        _id: 1, user_id: 1, course_id: 1, completed_lessons: 1, progress_percentage: 1, last_accessed: 1, last_lesson_completed: 1, total_time_spent: 1,
        // 展平关联字段到顶层
        user_name: '$userInfo.name',     // 直接映射嵌套字段到顶层
        course_title: '$courseInfo.title',     // 直接映射嵌套字段到顶层
        // 如需保留原type_id可添加: type_id: '$typeInfo._id'
        }
      }
    ]);
    return { rows, total };
  } catch (error) {
    throw { message: '获取课程进度列表失败', error };
  }
}
courseProgressSchema.statics.updateProgress = async function (id, progress) {
  try {
    return await this.findByIdAndUpdate(id, progress);
  } catch (error) {
    throw { message: '更新课程进度失败', error };
  }
}
// 获取课程进度分析
courseProgressSchema.statics.getProgressAnalytics = async function (user_id, course_id) {
  return await this.updateOne({ user_id, course_id }, { published: true });
}
module.exports = mongoose.model('CourseProgress', courseProgressSchema);
